package com.songcan.common.context;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import static com.songcan.common.contans.CoreContants.*;

/**
 * 业务服务全局拦截，获取当前线程存储对象
 */
public class JwtFilter implements Filter {

    private RedisTemplate redisTemplate;
    public JwtFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void init(FilterConfig filterConfig) {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, IOException {
        UserContext.remove();
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        String accessToken = request.getHeader(CORE_HEADER);
        String deptIds = request.getHeader(CORE_ORGANIZATION);
        String roles = request.getHeader(CORE_ROLE);
        if (null == accessToken) {
            accessToken = response.getHeader(CORE_HEADER);
        }

        if(!StringUtils.isEmpty(accessToken)){
            String userId = request.getHeader(CORE_USER);
            if(Objects.nonNull(deptIds)&& StrUtil.isNotEmpty(deptIds)){
                UserContext.set(userId, JSONArray.parseObject(deptIds,HashSet.class),JSONArray.parseObject(roles, List.class));
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
